<template>
  <BasicModal title="提醒记录" @register="registerModal" @ok="handleSubmit" :showOkBtn="title === '详情' ? false : true ">
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { getUpdateServiceReminder, getSearchDevices, getCreateServiceReminder } from '@/api/page/manage_account';
  import { ref } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  const emit = defineEmits(['next', 'register']);
  const schemas: FormSchema[] = [
    {
      label: '会员名',
      field: 'memberName',
      component: 'Input',
      required: true,
      colProps: {
        span: 24,
      },
    },
    {
      label: '设备名称',
      field: 'device',
      component: 'Select',
      required: true,
      colProps: {
        span: 24,
      },
    },
    {
      label: '设备型号',
      field: 'deviceModel',
      component: 'Select',
      required: true,
      colProps: {
        span: 24,
      },
    },
    {
      label: '购买渠道',
      field: 'channel',
      component: 'Input',
      required: false,
      colProps: {
        span: 24,
      },
    },
    {
      label: '订单ID',
      field: 'orderId',
      component: 'Input',
      required: false,
      colProps: {
        span: 24,
      },
    },
    {
      label: '配件金额',
      field: 'money',
      component: 'Input',
      required: false,
      colProps: {
        span: 24,
      },
    },
    {
      label: '服务时间',
      field: 'reminderDate',
      component: 'DatePicker',
      required: true,
      colProps: {
        span: 24,
      },
    },
    {
      label: '沟通记录',
      field: 'communicationRecords',
      component: 'Input',
      required: false,
      colProps: {
        span: 24,
      },
    },
  ];
  const title = ref<String>('');
  const id = ref<String>('');
  const details = ref<object>({});
  const [registerModal, { closeModal }] = useModalInner((data) => {
    resetFields();
    console.log(data);
    
    title.value = data.title || '';
    id.value = data.id.id || '';
    details.value = data.record || {};
    if (data?.details) {
      updateForm(updateSchema, schemas, true);
    } else {
      updateForm(updateSchema, schemas, false);
    }

    // 类别的选项
    getSearchDevices({}).then((res) => {
      if (res.code === 1000) {
        let deviceOption = <any>[];
        let deviceModelOption = <any>[];
        res.obj.forEach((item) => {
          deviceOption.push({
            label: item.deviceName,
            value: item.deviceName,
            key: item.deviceName,
          });
          deviceModelOption.push({
            label: item.deviceModel,
            value: item.deviceModel,
            key: item.deviceModel,
            device: item.deviceName,
          });
        });
        deviceOption = [...new Set(deviceOption)];
        deviceOption = deviceOption.filter((item, index) => {
          return deviceOption.findIndex((obj) => obj.label === item.label) === index;
        });
        updateSchema({
          field: 'device',
          componentProps: {
            options: deviceOption,
            onChange: (e: any) => {
              setFieldsValue({
                deviceModel: '',
              });
              let selectDeviceModelOption = <any>[];
              selectDeviceModelOption = deviceModelOption.filter((item) => {
                return item.device === e;
              });
              updateSchema({
                field: 'deviceModel',
                componentProps: {
                  options: selectDeviceModelOption,
                },
              });
            },
          },
        });
      }
    });

    data.record &&
      setFieldsValue({
        ...data.record,
      });
  });

  const [registerForm, { setFieldsValue, updateSchema, validate, resetFields }] = useForm({
    labelWidth: 120,
    schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
    submitFunc: handleGetValues,
  });

  const updateForm = (updateFn, schemas: FormSchema[], bool: boolean) => {
    updateFn(
      schemas.map((item) => ({
        field: item.field,
        componentProps: {
          disabled: bool,
        },
      })),
    );
  };

  async function handleGetValues() {
    try {
      const values = await validate();
      if (title.value === '添加') {
        const params = Object.assign({}, values, {customerManagentId: id.value});
        getCreateServiceReminder(params).then((res) => {
          if (res.code === 1000) {
            createMessage.success('添加成功！');
            emit('next', values);
            closeModal();
          } else {
            createMessage.error('添加失败，请重试！');
          }
        });
      } else {
        let params = Object.assign({}, details.value, values);
        params = Object.assign({}, params, { createType: 1 });
        const data = await getUpdateServiceReminder(params);
        if (data.code === 1000) {
          createMessage.success('修改成功！');
          closeModal();
          emit('next', values);
        } else {
          createMessage.error('修改失败，请重试！');
        }
      }
    } catch (error) {
      createMessage.error('请将有红色标记的填写完整');
    }
  }
  async function handleSubmit() {
    handleGetValues();
  }
</script>
